package com.health.interceptor;

import com.health.constant.MessageConstant;
import com.health.context.BaseContext;
import com.health.exception.UserNotLoginException;
import com.health.properties.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RestController
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(jwtProperties.getUserTokenName());
        Object userId = redisTemplate.opsForValue().get(jwtProperties.getUserTokenName() + token);
        log.info("token的值1：{}", token);
        //判断是否存在token
        if (!StringUtils.hasText(token)) {
            return false;
           // throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }

        if (userId== null){
            //throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
            return false;
        }
        BaseContext.setCurrentId(Long.valueOf(userId.toString()));
        return true;

    }
}
